package com.example.ffmpeg;

import ws.schild.jave.process.ProcessWrapper;
import ws.schild.jave.process.ffmpeg.DefaultFFMPEGLocator;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FFMpegUtil {



    public static boolean convertAndReplace(String filePath) throws IOException {
        filePath = filePath.replaceAll("\\\\","/");
        if (':'==filePath.charAt(2)){
            filePath=filePath.substring(1);
        }
        String tempFilePath = filePath.substring(0,filePath.length()-4) + "main_3.1_convert.mp4";
        File tempFile = new File(tempFilePath);
        // Execute FFmpeg command for conversion to temporary file
        ProcessWrapper ffmpeg = new DefaultFFMPEGLocator().createExecutor();
        ffmpeg.addArgument("-i");
        ffmpeg.addArgument(filePath);
        ffmpeg.addArgument("-vcodec");
        ffmpeg.addArgument("libx264");
        ffmpeg.addArgument("-profile:v");
        ffmpeg.addArgument("main");
        ffmpeg.addArgument("-level:v");
        ffmpeg.addArgument("3.1");
        ffmpeg.addArgument(tempFilePath);
        ffmpeg.execute();



        try (BufferedReader br = new BufferedReader(new InputStreamReader(ffmpeg.getErrorStream()))) {
            blockFfmpeg(br);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        if (!tempFile.exists()) {
            throw new IOException("Conversion failed, temporary file does not exist: " + tempFilePath);
        }
        //Files.move(Paths.get(tempFilePath), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);

        return true;
    }

    private static void blockFfmpeg(BufferedReader br) throws IOException {
        String line;
        // 该方法阻塞线程，直至合成成功
        while ((line = br.readLine()) != null) {
            doNothing(line);
        }
    }

    private static void doNothing(String line) {
        System.out.println(line);
    }

    public static void main(String[] args) throws IOException {
        FFMpegUtil.convertAndReplace("D:\\Desktop\\1.mp4");
    }

}
